<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="关联课程" prop="trainingId">
        <el-select v-model="queryParams.trainingId" placeholder="请选择关联课程" clearable filterable>
            <el-option
                v-for="item in trainingList"
                :key="item.id"
                :label="item.chapter"
                :value="item.id">
                <span style="float: left">{{ item.chapter }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.code }}</span>
            </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="题目内容" prop="question">
        <el-input
          v-model="queryParams.question"
          placeholder="请输入题目内容"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="questionList">
      <el-table-column label="ID" align="center" prop="id" width="80"/>
      <el-table-column label="题目" prop="question" :show-overflow-tooltip="true" />
      <el-table-column label="题目类型" prop="questionType" width="100" align="center">
        <template slot-scope="scope">
            <el-tag :type="getQuestionTypeTag(scope.row.questionType)">
                {{ formatQuestionType(scope.row.questionType) }}
            </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="关联课程" prop="trainingId" :formatter="trainingIdFormatter" />
      <el-table-column label="选项" prop="options" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          {{ formatOptions(scope.row.options) }}
        </template>
      </el-table-column>
      <el-table-column label="答案" prop="answer" width="150" align="center">
        <template slot-scope="scope">
          <!-- 问答题：答案过长时显示省略，支持hover查看完整内容 -->
          <el-popover
            v-if="scope.row.questionType === 'essay' && scope.row.answer && scope.row.answer.length > 20"
            placement="top"
            width="300"
            trigger="hover">
            <div style="max-height: 200px; overflow-y: auto; white-space: pre-wrap; word-break: break-word;">
              {{ scope.row.answer }}
            </div>
            <span slot="reference" style="cursor: pointer; color: #409EFF;">
              {{ scope.row.answer.substring(0, 20) }}...
            </span>
          </el-popover>
          <!-- 非问答题或答案较短：直接显示 -->
          <span v-else>{{ scope.row.answer }}</span>
        </template>
      </el-table-column>
      <el-table-column label="分值" prop="score" width="80" align="center" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改题目对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="题目类型" prop="questionType">
            <el-radio-group v-model="form.questionType" @change="handleQuestionTypeChange">
                <el-radio label="multiple_choice">单选题</el-radio>
                <el-radio label="multiple_select">多选题</el-radio>
                <el-radio label="true_false">判断题</el-radio>
                <el-radio label="essay">问答题</el-radio>
            </el-radio-group>
        </el-form-item>
         <el-form-item label="关联课程" prop="trainingId">
            <el-select v-model="form.trainingId" placeholder="请选择关联课程" filterable>
                <el-option
                    v-for="item in trainingList"
                    :key="item.id"
                    :label="item.chapter"
                    :value="item.id">
                     <span style="float: left">{{ item.chapter }}</span>
                     <span style="float: right; color: #8492a6; font-size: 13px">{{ item.code }}</span>
                </el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="题目内容" prop="question">
          <el-input v-model="form.question" type="textarea" placeholder="请输入题目内容" />
        </el-form-item>
        <el-form-item label="题目分值" prop="score">
          <el-input-number v-model="form.score" :min="1" :max="100" placeholder="请输入题目分值" style="width: 100%" />
        </el-form-item>
        <div v-if="form.questionType === 'multiple_choice' || form.questionType === 'multiple_select'">
            <el-form-item
              v-for="(option, index) in form.options"
              :key="option.key"
              :label="'选项 ' + option.label"
              :prop="'options.' + index + '.value'"
              :rules="{ required: true, message: '选项内容不能为空', trigger: 'blur' }">
              <el-input v-model="option.value" placeholder="请输入选项内容" style="width: 85%; margin-right: 10px;"></el-input>
              <el-button @click.prevent="removeOption(option)" icon="el-icon-minus" circle plain size="mini"></el-button>
            </el-form-item>
             <el-form-item>
              <el-button @click="addOption" type="dashed" icon="el-icon-plus">添加选项</el-button>
            </el-form-item>
        </div>
        <el-form-item label="正确答案" prop="answer">
            <el-radio-group v-model="form.answer" v-if="form.questionType === 'multiple_choice'">
                <el-radio v-for="option in form.options" :key="option.label" :label="option.label">{{ option.label }}</el-radio>
            </el-radio-group>
             <el-checkbox-group v-model="form.answerArray" v-if="form.questionType === 'multiple_select'">
                <el-checkbox v-for="option in form.options" :key="option.label" :label="option.label">{{ option.label }}</el-checkbox>
            </el-checkbox-group>
            <el-radio-group v-model="form.answer" v-if="form.questionType === 'true_false'">
                <el-radio label="T">正确</el-radio>
                <el-radio label="F">错误</el-radio>
            </el-radio-group>
            <el-input v-model="form.answer" v-if="form.questionType === 'essay'" type="textarea" placeholder="请输入标准答案（用于参考）" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listQuestions, addQuestion, updateQuestion, delQuestion, listTraining } from "@/api/system/training";

export default {
  name: "TestQuestion",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 题目表格数据
      questionList: [],
      // 课程列表
      trainingList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        trainingId: null,
        question: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        trainingId: [{ required: true, message: "必须关联一个课程", trigger: "change" }],
        question: [{ required: true, message: "题目内容不能为空", trigger: "blur" }],
        score: [{ required: true, message: "题目分值不能为空", trigger: "blur" }],
        answer: [{ required: true, message: "请选择一个正确答案", trigger: "blur" }]
      }
    };
  },
  created() {
    this.getList();
    this.getTrainingList();
  },
  methods: {
    /** 查询题目列表 */
    getList() {
      this.loading = true;
      listQuestions(this.queryParams).then(response => {
        this.questionList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询所有课程用于关联 */
    getTrainingList() {
        listTraining({ pageNum: 1, pageSize: 1000 }).then(response => {
            this.trainingList = response.rows;
        });
    },
    formatQuestionType(type) {
        if (type === 'true_false') return '判断题';
        if (type === 'multiple_select') return '多选题';
        if (type === 'essay') return '问答题';
        return '单选题';
    },
    getQuestionTypeTag(type) {
        if (type === 'true_false') return 'info';
        if (type === 'multiple_select') return 'success';
        if (type === 'essay') return 'warning';
        return 'primary';
    },
    trainingIdFormatter(row, column) {
        const training = this.trainingList.find(t => t.id === row.trainingId);
        return training ? training.chapter : row.trainingId;
    },
    formatOptions(optionsStr) {
      try {
        const options = JSON.parse(optionsStr);
        return Object.entries(options).map(([key, value]) => `${key}: ${value}`).join('; ');
      } catch (e) {
        return optionsStr;
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        trainingId: null,
        questionType: 'multiple_choice',
        question: '',
        score: 5,
        options: [
            { key: Date.now(), label: 'A', value: '' },
            { key: Date.now() + 1, label: 'B', value: '' }
        ],
        answer: '',
        answerArray: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加题目";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      // 直接使用行数据，但需要解析options
      this.form.id = row.id;
      this.form.trainingId = row.trainingId;
      this.form.question = row.question;
      this.form.answer = row.answer;
      this.form.score = row.score || 5;
      this.form.questionType = row.questionType || 'multiple_choice';

      if (this.form.questionType === 'multiple_choice' || this.form.questionType === 'multiple_select') {
        if (this.form.questionType === 'multiple_select' && row.answer) {
            this.form.answerArray = row.answer.split(',');
        } else {
            this.form.answerArray = [];
        }
        try {
        const optionsObj = JSON.parse(row.options);
        this.form.options = Object.entries(optionsObj).map(([label, value], index) => ({
            key: Date.now() + index,
            label,
            value
        }));
        } catch (e) {
          this.form.options = [];
        }
      } else {
        this.form.options = [];
      }

      this.open = true;
      this.title = "修改题目";
    },
    /** 提交按钮 */
    submitForm() {
      // 在提交前，根据题目类型处理答案
      if (this.form.questionType === 'multiple_select') {
          this.form.answer = this.form.answerArray.sort().join(',');
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          let optionsObj = {};
          if (this.form.questionType === 'multiple_choice' || this.form.questionType === 'multiple_select') {
            optionsObj = this.form.options.reduce((acc, opt) => {
                acc[opt.label] = opt.value;
                return acc;
            }, {});
          } else if (this.form.questionType === 'true_false') {
            optionsObj = { 'T': '正确', 'F': '错误' };
          } else if (this.form.questionType === 'essay') {
            optionsObj = {};
          }

          const formData = {
              ...this.form,
              options: JSON.stringify(optionsObj)
          }

          if (this.form.id != null) {
            updateQuestion(formData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addQuestion(formData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id;
      this.$modal.confirm('是否确认删除题目ID为"' + ids + '"的数据项？').then(function() {
        return delQuestion(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    addOption() {
      const newLabel = String.fromCharCode(65 + this.form.options.length);
      this.form.options.push({
        key: Date.now(),
        label: newLabel,
        value: ''
      });
    },
    removeOption(item) {
        var index = this.form.options.indexOf(item);
        if (index !== -1) {
            this.form.options.splice(index, 1);
            // Re-label options
            this.form.options.forEach((opt, i) => {
                opt.label = String.fromCharCode(65 + i);
            });
            // reset answer if it was the removed option
            if (this.form.questionType !== 'multiple_select' && this.form.answer === item.label) {
                this.form.answer = '';
            }
            // reset answer array for multi-select
            const answerIndex = this.form.answerArray.indexOf(item.label);
            if (answerIndex > -1) {
                this.form.answerArray.splice(answerIndex, 1);
            }
        }
    },
    handleQuestionTypeChange() {
        this.form.answer = '';
        this.form.answerArray = [];
    }
  }
};
</script> 